<template>
  <div style="margin-top: 16px">
      <el-form :model="muleTaskForm" label-width="100px" size="small" >
        <el-form-item label="终端" prop="endpointUrl" :rules="{ required: true, trigger: ['blur', 'change'] }">
          <el-input v-model="muleTaskForm.endpointUrl" placeholder="需要调用的Mule终端" clearable @change="updateElementTask()"></el-input>
        </el-form-item>
          <el-form-item label="语言" prop="language" :rules="{ required: true, trigger: ['blur', 'change'] }">
            <el-input v-model="muleTaskForm.language" placeholder="要使用解析荷载表达式(payloadExpression)属性的语言" clearable @change="updateElementTask()"></el-input>
          </el-form-item>
          <el-form-item label="表达式" prop="payloadExpression" :rules="{ required: true, trigger: ['blur', 'change'] }">
            <el-input v-model="muleTaskForm.payloadExpression" placeholder="作为消息荷载的表达式" clearable @change="updateElementTask()"></el-input>
          </el-form-item>
          <el-form-item label="结果变量" prop="resultVariable">
            <el-input v-model="muleTaskForm.resultVariable" placeholder="将要保存调用结果的变量名称" clearable @change="updateElementTask()"></el-input>
          </el-form-item>
      </el-form>
  </div>
</template>

<script>
export default {
  name: "MuleTaskPanel",
  props: {
    id: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      muleTaskForm: {
        endpointUrl: '',
        language: '',
        payloadExpression: '',
        resultVariable: '',
      },
    }
  },
  watch: {
    id: {
      immediate: true,
      handler() {
        this.$nextTick(() => this.resetTaskForm());
      }
    }
  },
  methods: {
    resetTaskForm() {
      const {muleTaskForm} = this;
      // 获取注入字段
      const fieldsList = this.modelerStore.element.businessObject?.extensionElements?.values?.filter(ex => ex.$type === `flowable:Field`) ?? [];
      if (fieldsList && fieldsList.length > 0) {
        fieldsList.forEach(field => {
          muleTaskForm[field.name] = field.string;
        })
      }
    },

    // 创建扩展属性
    updateElementTask() {
      const fieldsList = [];
      for (let key in this.muleTaskForm) {
        const value = this.muleTaskForm[key];
        if (value) {
          const fieldConfig = {name: key, string: value};
          const mailFrom = this.modelerStore.moddle.create(`flowable:Field`, fieldConfig);
          fieldsList.push(mailFrom);
        }
      }

      this.updateElementExtensions(fieldsList);
      this.mailModelVisible = false;
    },

    // 更新扩展属性
    updateElementExtensions(extensionList) {
      const extensions = this.modelerStore.moddle.create("bpmn:ExtensionElements", {
        values: extensionList
      });
      this.modelerStore.modeling.updateProperties(this.modelerStore.element, {
        extensionElements: extensions
      });
    },
  },
};
</script>
